package cn.tedu.baidashi.controller;

import cn.tedu.baidashi.model.User;
import cn.tedu.baidashi.service.ICartService;
import cn.tedu.baidashi.service.IUserService;
import cn.tedu.baidashi.vo.CartVO;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/carts")
public class CartController {

    @Resource
    private IUserService userService;
    @Resource
    private ICartService cartService;

    /**
     *获得购物车
     * @return
     */
    @GetMapping("/my")
    public CartVO getMyCart(@AuthenticationPrincipal UserDetails userDetails){
        User user=userService.getUser(userDetails.getUsername());
        CartVO cartVO = cartService.getCart(user.getId());
        System.out.println(cartVO);
        return cartVO;
    }

    /**
     *增加商品到购物车
     * @param itemsId
     * @param quantity
     * @return
     */
    @GetMapping("/add/{itemsId}/{quantity}")
    public String addItemsToCart(@AuthenticationPrincipal UserDetails userDetails,
                                 @PathVariable Integer itemsId,
                                 @PathVariable Integer quantity){
        User user=userService.getUser(userDetails.getUsername());
        cartService.addCart(user.getId(), itemsId, quantity);
        return "ok";
    }

    /**
     *修改购物车中的商品数量
     * @param itemsId
     * @param quantity
     * @return
     */
    @GetMapping("/update/{itemsId}/{quantity}")
    public String updateQuantity(@AuthenticationPrincipal UserDetails userDetails,
                                 @PathVariable Integer itemsId,
                                 @PathVariable Integer quantity){
        User user = userService.getUser(userDetails.getUsername());
        cartService.updateCount(user.getId(), itemsId, quantity);
        return "ok";
    }

    /**
     *删除购物车中的商品
     * @param itemsId
     * @return
     */
    @GetMapping("/delete/{itemsId}")
    public String deleteItems(@AuthenticationPrincipal UserDetails userDetails,
                              @PathVariable Integer itemsId){
        User user=userService.getUser(userDetails.getUsername());
        cartService.deleteCart(user.getId(),itemsId);
        return "ok";
    }
}
